<template>
    <!-- 客户详细 -->
    <div class="customer-detail">
      <!-- 上方容器：客户基础资料 -->
      <div class="basic-info-container">
        <div class="section-header">
          <div class="section-title">客户基础资料</div>
          <div class="section-actions">
            <el-button size="small" @click="JumptoEdit">编辑</el-button>
            <el-button size="small" @click="deletecustomer">删除</el-button>
            <el-button @click="UpdateStatus(customerForm.cust_status)" size="small">
              {{ customerForm.cust_status === 0 ? '停用' : '启用' }}
            </el-button>
          </div>
        </div>
        
        <div class="divider"></div>
        
        <!-- 使用网格布局的基础资料部分 -->
        <div class="basic-info-grid">
          
          <div class="info-item">
            <div class="info-label">所属行业</div>
            <div class="info-value">{{customerForm.cust_industry}}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">客户来源</div>
            <div class="info-value">{{customerForm.cust_source}}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">联系人</div>
            <div class="info-value">{{ customerForm.cust_linkman }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">状态</div>
            <div class="info-value">{{ customerForm.cust_status === 1 ? '停用' : '启用' }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">联系电话</div>
            <div class="info-value">{{ customerForm.cust_linkphone }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">电子邮箱</div>
            <div class="info-value">{{ customerForm.cust_email }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">销售部门</div>
            <div class="info-value">{{ customerForm.cust_depName }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">销售负责人</div>
            <div class="info-value">{{ customerForm.cust_userName }}</div>
          </div>
          
          <!-- 地址跨2列 -->
          <div class="info-item full-row">
            <div class="info-label">客户地址</div>
            <div class="info-value">{{ customerForm.cust_address }}</div>
          </div>
          
          <!-- 备注跨2列 -->
          <div class="info-item full-row">
            <div class="info-label">备注</div>
            <div class="info-value">{{ customerForm.remark }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">创建人</div>
            <div class="info-value">{{ customerForm.create_name }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">创建时间</div>
            <div class="info-value">{{ customerForm.create_time }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">更新人</div>
            <div class="info-value">{{ customerForm.update_name }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">更新时间</div>
            <div class="info-value">{{ customerForm.update_time }}</div>
          </div>
        </div>
      </div>
      
      <!-- 下方容器：其他信息 -->
      <div class="other-info-container">
        <div class="section-header">
          <div class="section-tabs">
            <div 
              v-for="(tab, index) in tabs" 
              :key="index"
              :class="['tab-item', { active: activeTab === tab }]"
              @click="activeTab = tab"
            >
              {{ tab }}
            </div>
          </div>
        </div>
        
        <div class="divider"></div>
        
        <div v-if="activeTab === '其他信息'" class="tab-content">
          <!-- 使用网格布局的基础资料部分 -->
          <div class="section-header">
            <div class="section-title">财务信息</div>
          </div>
          <div class="Additional-Information">
            <div class="info-item">
              <div class="info-label">账户名称</div>
              <div class="info-value">{{customerForm.cust_accountName}}</div>
            </div>
            
            <div class="info-item">
              <div class="info-label">纳税人识别号</div>
              <div class="info-value">{{customerForm.cust_taxpayerNum}}</div>
            </div>
            
            <div class="info-item">
              <div class="info-label">银行账户</div>
              <div class="info-value">{{ customerForm.cust_bankAccount }}</div>
            </div>
            
            <div class="info-item">
              <div class="info-label">开户银行</div>
              <div class="info-value">{{ customerForm.cust_openBank }}</div>
            </div>
            
            <div class="info-item">
              <div class="info-label">开户行地址</div>
              <div class="info-value">{{ customerForm.cust_openBankAddress }}</div>
            </div>
          </div>
          <div class="section-header">
            <div class="section-title">附件</div>
          </div>
          <el-table 
            :data="filelist" 
            @row-click="handleRowClick"
            style="width: 100%"
            >
            <el-table-column label="文件名">
              <template #default="scope">
                <el-link type="primary" :underline="false">
                  <el-icon><Document /></el-icon>
                  <span style="margin-left: 8px">{{ scope.row.title }}</span>
                </el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="activeTab === '销售记录'" class="tab-content">
            <!-- 导出按钮 -->
            <div style="text-align: left; margin-bottom: 10px;">
                <el-button @click="saleExport">导出</el-button>
            </div>
            <!-- 表格展示 -->
            <el-table :data="saledatadata" stripe style="margin-top: 10px;" @selection-change="saleSelectChange">
                <!-- 选择列 -->
                <el-table-column fixed type="selection" width="55"></el-table-column>
                <!-- 序号列 -->
                <el-table-column fixed type="index" label="序号" width="80"></el-table-column>
                <!-- 销售单号列 (可点击跳转) -->
                <el-table-column  label="销售单号" width="200px" fixed>
                    <template #default="scope">
                        <span style="color: green; cursor: pointer;" @click="ShowSaleInfo(scope.row)">
                            {{ scope.row.sale_code }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column fixed prop="sale_date" label="销售日期" width="180px"></el-table-column>
                <!-- 其他列 -->
                <el-table-column prop="sale_status" label="单据状态" width="120px"></el-table-column>
                <el-table-column prop="cust_name" label="客户名称" width="150px"></el-table-column>
                <el-table-column prop="cust_linkman" label="联系人" width="120px"></el-table-column>
                <el-table-column prop="cust_linkphone" label="联系方式" width="150px"></el-table-column>
                <el-table-column prop="sale_depName" label="销售部门" width="120px"></el-table-column>
                <el-table-column prop="sale_userName" label="销售负责人" width="120px"></el-table-column>
                <el-table-column prop="sale_num" label="销售数量" width="100px"></el-table-column>
                <el-table-column prop="sale_total" label="销售金额" width="120px"></el-table-column>
                <el-table-column label="销售货品" width="250px">
                    <template #default="scope">
                        <el-tooltip
                            effect="dark"
                            :content="scope.row.proc_list_full"
                            placement="top"
                            :disabled="!scope.row.proc_list_full || scope.row.proc_list_full.split('、').length <= 3"
                        >
                            <span>{{ scope.row.proc_list }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column prop="create_name" label="制单人" width="120px"></el-table-column>
                <el-table-column prop="create_time" label="制单时间" width="180px"></el-table-column>
                <el-table-column prop="approver_name" label="审核人" width="120px"></el-table-column>
                <el-table-column prop="approver_time" label="审核时间" width="180px"></el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                :page-size="10"
                :pager-count="11"
                layout="prev, pager, next, jumper"
                :total="salerows"
                v-on:current-change="salehandlePageChange"
                style="float:right; margin-top:20px;">
            </el-pagination>
        </div>
        <div v-if="activeTab === '出库记录'" class="tab-content">
          <!-- 导出按钮 -->
          <div style="text-align: left; margin-bottom: 10px;">
              <el-button @click="outExport">导出</el-button>
          </div>

          <!-- 表格展示 -->
          <el-table :data="outstockdata" stripe style="margin-top: 10px;" @selection-change="outSelectChange">
              <!-- 固定列和数据展示列 -->
              <el-table-column fixed type="selection"></el-table-column>
              <el-table-column fixed type="index" label="序号" width="80"></el-table-column>
              <el-table-column fixed label="出库单号" width="200px">
                  <template #default="scope">
                      <span style="color: green; cursor: pointer;" @click="ShowOutstockInfo(scope.row)">
                          {{ scope.row.out_code }}
                      </span>
                  </template>
              </el-table-column>
              <el-table-column fixed prop="out_type" label="出库类型"></el-table-column>
              <el-table-column fixed prop="out_status" label="状态"></el-table-column>
              <el-table-column fixed prop="out_date" label="出库日期" width="180px"></el-table-column>
              <el-table-column prop="wh_name" label="仓库名称" width="150px"></el-table-column>
              <el-table-column prop="out_order" label="关联单号" width="200px"></el-table-column>
              <el-table-column label="出库货品" width="300px">
                  <template #default="scope">
                      <el-tooltip
                          effect="dark"
                          :content="scope.row.proc_list_full"
                          placement="top"
                          :disabled="!scope.row.proc_list_full || scope.row.proc_list_full.split('、').length <= 3"
                      >
                          <span>{{ scope.row.proc_list }}</span>
                      </el-tooltip>
                  </template>
              </el-table-column>
              <el-table-column prop="out_user" label="经办人"></el-table-column>
              <el-table-column prop="out_num" label="出库数量"></el-table-column>
              <el-table-column prop="out_total" label="出库金额" width="120px"></el-table-column>
              <el-table-column prop="create_name" label="制单人"></el-table-column>
              <el-table-column prop="create_time" label="制单时间" width="200px"></el-table-column>
              <el-table-column prop="approver_name" label="审核人"></el-table-column>
              <el-table-column prop="approver_time" label="审核时间" width="200px"></el-table-column>
          </el-table>
        </div>
        <div v-if="activeTab === '入库记录'" class="tab-content">
          <!--仅保留导出按钮和表格展示-->
          <div style="text-align: left; margin-bottom: 10px;">
              <el-button @click="inExport">导出</el-button>
          </div>

          <!--表格展示部分保留只读展示-->
          <el-table :data="instockdata" stripe style="margin-top: 10px;" @selection-change="inSelectChange">
              <!--固定列和数据展示列保留-->
              <el-table-column fixed type="selection"></el-table-column>
              <el-table-column fixed type="index" label="序号" width="100"></el-table-column>
              <el-table-column fixed label="入库单号" width="200px">
                  <template #default="scope">
                      <span style="color: green; cursor: pointer;" @click="ShowInstockInfo(scope.row)">
                          {{ scope.row.in_code }}
                      </span>
                  </template>
              </el-table-column>
              <el-table-column fixed prop="in_type" label="入库类型"></el-table-column>
              <el-table-column fixed prop="in_status" label="状态"></el-table-column>
              <el-table-column fixed prop="in_date" label="入库日期" width="200px"></el-table-column>
              <el-table-column prop="wh_name" label="仓库名称" width="200px"></el-table-column>
              <el-table-column prop="in_order" label="关联单号" width="200px"></el-table-column>
              <el-table-column label="入库货品" width="300px">
                  <template #default="scope">
                      <el-tooltip
                          effect="dark"
                          :content="scope.row.proc_list_full"
                          placement="top"
                          :disabled="!scope.row.proc_list_full || scope.row.proc_list_full.split('、').length <= 3"
                      >
                          <span>{{ scope.row.proc_list }}</span>
                      </el-tooltip>
                  </template>
              </el-table-column>
              <el-table-column prop="in_user" label="经办人"></el-table-column>
              <el-table-column prop="in_num" label="入库数量"></el-table-column>
              <el-table-column prop="in_total" label="入库金额" width="120px"></el-table-column>
              <el-table-column prop="create_name" label="制单人"></el-table-column>
              <el-table-column prop="create_time" label="制单时间" width="200px"></el-table-column>
              <el-table-column prop="approver_name" label="审核人"></el-table-column>
              <el-table-column prop="approver_time" label="审核时间" width="200px"></el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 底部操作栏 -->
      <div class="action-bar">
        <el-button @click="Close">关闭</el-button>
      </div>
    </div>
  </template>
  
  <script>
  import { useRouter, useRoute } from 'vue-router'
  import {ref,reactive,onMounted} from 'vue';
  import http from '../auth/index';
  import { ElMessage,ElMessageBox  } from 'element-plus'; //提示信息
  import { Document } from '@element-plus/icons-vue'
  import * as XLSX from 'xlsx';
  export default {
    setup(){
      const router = useRouter();
      const route = useRoute(); // 获取路由实例
      const id = ref(route.query ? route.query.id || null : null);
      function formatDateTime(date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
  
      // 选项卡数据
      const tabs = ['其他信息', '销售记录', '出库记录', '入库记录'];
      const activeTab = ref('其他信息');
  
      // 过滤条件
      const filter = reactive({
        operationType: '',
        operator: '',
        operationTime: ''
      });
  
      // 操作记录数据
      const filelist = ref([])//附件存储数组
  
      // 行点击事件
      function handleRowClick(row) {
        if (!row.file_name) {
          ElMessage.error('文件URL不存在，请重新上传');
          return;
        }
  
        const ext = row.title.split('.').pop().toLowerCase();
  
        switch (ext) {
          case 'jpg':
          case 'jpeg':
          case 'png':
          case 'gif':
          case 'bmp':
          case 'pdf':
          case 'doc':
          case 'docx':
          case 'xls':
          case 'xlsx':
          case 'ppt':
          case 'txt':
          case 'pptx':
            window.open(row.file_name, '_blank');
            break;
          default:
            const link = document.createElement('a');
            link.href = row.file_name;
            link.download = row.title;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
      }
  
      // 获取附件数据的方法
      function GetPublicFile() {
        const code = route.query ? route.query.code || null : null
        http.get("/PublicFile/GetPublicFileBy", {
          params: {
            type: "客户",
            code: code,
          }
        }).then(res => {
          // 根据映射类调整数据结构
          console.log("附件:", res.data); // 调试用
          filelist.value = res.data;
        }).catch(err => {
          console.log(err)
          ElMessage.error('附件加载失败')
        })
      }
  
      const pageSize = ref(10);
      const totalItems = ref(100);
  
      const customerForm = reactive({
        cust_code: "",
        cust_name: "",
        cust_industry: "",
        cust_source: "",
        cust_linkman: "",
        cust_linkphone: "",
        cust_email: "",
        cust_depId: null,
        cust_userId: null,
        cust_status: 0,
        cust_address: "",
        remark: "",
        cust_accountName: "",
        cust_taxpayerNum: "",
        cust_bankAccount: "",
        cust_openBank: "",
        cust_openBankAddress: "",
        create_name: "",
        create_time: "",
        update_name: "",
        update_time: "",
        cust_depName:"",
        cust_userName:""
      });
  
      // 查询Id查客户数据
      function GetIdcustomer() {
        http.get("/customer/GetIdcustomer", {
            params: {
                id: id.value
            }
        }).then(res => {
            const apiData = res.data;
            console.log("ID客户:", apiData); // 调试用
            Object.assign(customerForm, processcustomerData(apiData));
        }).catch(err => {
            console.log(err);
            ElMessage.error('数据加载失败');
        });
      }
  
      // 封装数据处理逻辑
      function processcustomerData(apiData) {
        return {
          cust_code: apiData.cust_code || "",
          cust_name: apiData.cust_name || "",
          cust_industry: apiData.cust_industry || "",
          cust_source: apiData.cust_source || "",
          cust_linkman: apiData.cust_linkman || "",
          cust_linkphone: apiData.cust_linkphone || "",
          cust_email: apiData.cust_email || "",
          cust_depId: apiData.cust_depId || null,
          cust_userId: apiData.cust_userId || null,
          cust_status: apiData.cust_status || 0,
          cust_address: apiData.cust_address || "",
          remark: apiData.remark || "",
          cust_accountName: apiData.cust_accountName || "",
          cust_taxpayerNum: apiData.cust_taxpayerNum || "",
          cust_bankAccount: apiData.cust_bankAccount || "",
          cust_openBank: apiData.cust_openBank || "",
          cust_openBankAddress: apiData.cust_openBankAddress || "",
          create_name: apiData.create_name || "" ,
          create_time: apiData.create_time || "",
          update_name: apiData.update_name || "",
          update_time: apiData.update_time || "",
          cust_depName:apiData.cust_depName||"",
          cust_userName:apiData.cust_userName||""
        };
      }
  
      // 删除客户方法
      function deletecustomer() {
        ElMessageBox.confirm('确定要删除该客户吗？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
            try {
            // 调用后端逻辑删除接口（PUT 方法）
            const res = await http.put('/customer/Deletecustomer?id='+id.value);
            if (res.status === 200) {
                ElMessage.success('删除成功');
                router.push('customer');
            }
            } catch (err) {
            ElMessage.error('删除失败');
            console.error(err);
            }
        }).catch(() => {
            ElMessage.success('删除已取消');
        });
      }
  
      //启用/停用
      async function UpdateStatus(status) {
        ElMessageBox.confirm(customerForm.cust_status === 0 ? '确定要停用该客户吗？' : '确定要启用该客户吗？','提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
            try {
            const res = await http.put('/customer/UpdateStatus?cust_id='+id.value+'&cust_status='+status);
            if (res.status === 200) {
                ElMessage.success(customerForm.cust_status === 0 ? '成功停用' : '成功启用');
                GetIdcustomer()
            }
            } catch (err) {
            ElMessage.error(customerForm.cust_status === 0 ? '停用失败' : '启用失败');
            console.error(err);
            }
        }).catch(() => {
            ElMessage.success(customerForm.cust_status === 0 ? '停用已取消' : '启用已取消');
        });
      }
  
      function JumptoEdit() {
        router.push({ path: 'customernew', query: { id: id.value ,Detail:true} });
      }

        //#region 入库记录
        // 数据格式化工具函数保留
        function formatGoodsList(goods) {
            if (!goods) return "";
            const goodsArray = Array.isArray(goods) ? goods : goods.split('、').filter(Boolean);
            if (goodsArray.length <= 3) {
                return goodsArray.join('、');
            } else {
                const firstThree = goodsArray.slice(0, 3).join('、');
                return `${firstThree}等${goodsArray.length}项....`;
            }
        }

        // 表格数据相关
        const instockdata = ref([]);
        const incurrentPage = ref(1);
        const inselectdata = ref([]);

        // 初始化数据加载（无条件加载全部数据）
        function InLoadData() {
          http.get("/Instock_h/GetInstock_hCust", {
              params: { 
                CurrentPage:incurrentPage.value,
                cust_id:id.value
              }
          }).then(res => {
              // 添加空数组防护
              const listData = res.data?.list || [];
              
              const Data = listData.map(item => ({
                  ...item,
                  in_date: formatDateTime(new Date(item.in_date)),
                  create_time: formatDateTime(new Date(item.create_time)),
                  approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                  in_total: item.in_total ? Number(item.in_total).toFixed(2) : "0.00",
                  proc_list_full: item.proc_list,
                  proc_list: formatGoodsList(item.proc_list)
              }));
              
              instockdata.value = Data;
          }).catch(error => {
              console.error("加载入库记录失败:", error);
              ElMessage.error("加载入库记录失败");
              instockdata.value = [];
          });
        }

        // 分页处理
        function inhandlePageChange(page) {
            incurrentPage.value = page;
            InLoadData();
        }

        // 多选数据收集
        function inSelectChange(val) {
            inselectdata.value = val;
        }

        // 导出功能
        function inExport() {
            if (inselectdata.value.length == 0) {
                ElMessage({ message: '请选择要导出的数据.', type: 'warning' });
                return;
            }
            const wb = XLSX.utils.book_new();
            const excelData = inselectdata.value.map((row) => ({
                "入库单号": row.in_code,
                "入库类型": row.in_type,
                "状态": row.in_status,
                "入库日期": row.in_date,
                "仓库名称": row.wh_name,
                "关联单号": row.in_order,
                "入库货品": row.proc_list,
                "经办人": row.in_user,
                "入库数量": row.in_num,
                "入库金额": row.in_total,
                "制单人": row.create_name,
                "制单时间": row.create_time,
                "审核人": row.approver_name,
                "审核时间": row.approver_time
            }));
            const ws = XLSX.utils.json_to_sheet(excelData);
            XLSX.utils.book_append_sheet(wb, ws, "入库单");
            XLSX.writeFile(wb, `入库单${new Date().toLocaleDateString()}.xlsx`);
        }

        function ShowInstockInfo(row) {
          // 假设入库详情页的路由名称是 'instockinfo'，请根据实际路由配置调整
          console.log("入库跳转:", row); // 调试用
          router.push({
              name: "instockinfo",
              params: {
                  instockid: row.in_id,
                  instockcode: row.in_code
              }
          });
      }
      //#endregion

      //#region 出库记录
      function formatGoodsList(goods) {
          if (!goods) return "";
          const goodsArray = Array.isArray(goods) ? goods : goods.split('、').filter(Boolean);
          if (goodsArray.length <= 3) {
              return goodsArray.join('、');
          } else {
              const firstThree = goodsArray.slice(0, 3).join('、');
              return `${firstThree}等${goodsArray.length}项....`;
          }
      }

      // 表格数据相关
      const outstockdata = ref([]);
      const outcurrentPage = ref(1);
      const outselectdata = ref([]);

      // 初始化数据加载
      function OutLoadData() {
        http.get("/Outstock_h/GetOutstock_hCust", {
            params: { 
              CurrentPage:outcurrentPage.value,
              cust_id:id.value
            }
        }).then(res => {
            // 添加空数组防护
            const listData = res.data?.list || [];
            
            const Data = listData.map(item => ({
                ...item,
                out_date: formatDateTime(new Date(item.out_date)),
                create_time: formatDateTime(new Date(item.create_time)),
                approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                out_total: item.out_total ? Number(item.out_total).toFixed(2) : "0.00",
                proc_list_full: item.proc_list,
                proc_list: formatGoodsList(item.proc_list)
            }));
            
            outstockdata.value = Data;
        }).catch(error => {
            console.error("加载出库记录失败:", error);
            ElMessage.error("加载出库记录失败");
            outstockdata.value = [];
        });
      }

      // 分页处理
      function outhandlePageChange(page) {
          outcurrentPage.value = page;
          OutLoadData();
      }

      // 多选数据收集
      function outSelectChange(val) {
          outselectdata.value = val;
      }

      // 导出功能
      function outExport() {
          if (outselectdata.value.length == 0) {
              ElMessage({ message: '请选择要导出的数据.', type: 'warning' });
              return;
          }
          const wb = XLSX.utils.book_new();
          const excelData = outselectdata.value.map((row) => ({
              "出库单号": row.out_code,
              "出库类型": row.out_type,
              "状态": row.out_status,
              "出库日期": row.out_date,
              "仓库名称": row.wh_name,
              "关联单号": row.out_order,
              "出库货品": row.proc_list,
              "经办人": row.out_user,
              "出库数量": row.out_num,
              "出库金额": row.out_total,
              "制单人": row.create_name,
              "制单时间": row.create_time,
              "审核人": row.approver_name,
              "审核时间": row.approver_time
          }));
          const ws = XLSX.utils.json_to_sheet(excelData);
          XLSX.utils.book_append_sheet(wb, ws, "出库单");
          XLSX.writeFile(wb, `出库单${new Date().toLocaleDateString()}.xlsx`);
      }

      function ShowOutstockInfo(row) {
          // 假设出库详情页的路由名称是 'outstockinfo'，请根据实际路由配置调整
          router.push({
              name: "outstockinfo",
              params: {
                  outstockid: row.out_id,
                  outstockcode: row.out_code
              }
          });
      }
      //#endregion

      //#region 销售订单
      // 销售记录数据
      const saledatadata = ref([]);
      // 销售记录当前页
      const salecurrentPage = ref(1);
      // 销售记录总条数
      const salerows = ref(0);
      // 销售记录选中数据
      const saleselectdata = ref([]);

      // 货品列表格式化函数 (如果还没有的话，从销售订单文件复制过来)
      function formatProductList(products) {
          if (!products) return "";
          const productArray = Array.isArray(products)
              ? products
              : products.split('、').filter(Boolean);
          if (productArray.length <= 3) {
              return productArray.join('、');
          } else {
              const firstThree = productArray.slice(0, 3).join('、');
              return `${firstThree}等${productArray.length}项....`;
          }
      }

      // 日期转换格式 (如果还没有的话，从销售订单文件复制过来，或使用已有的 formatDateTime)
      function formatDateTimeForSale(dateInput) {
        if (!dateInput) return '';
        let date;
        if (typeof dateInput === 'string') {
          date = new Date(dateInput);
          if (isNaN(date.getTime())) {
            const timestamp = parseInt(dateInput);
            if (!isNaN(timestamp)) {
              date = new Date(timestamp);
            }
          }
        } else if (typeof dateInput === 'number') {
          date = new Date(dateInput);
        } else if (dateInput instanceof Date) {
          date = dateInput;
        }
        if (!date || isNaN(date.getTime())) {
          console.warn('无法解析日期:', dateInput);
          return dateInput || '';
        }
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }

      // 加载销售记录数据
      function SaleLoadData() {
        if (!id.value) {
            console.warn('客户ID无效，无法加载销售记录');
            saledatadata.value = [];
            salerows.value = 0;
            return;
        }
        http.get("/Sale_h/GetSale_h", {
            params: {
                cust: id.value, // 使用客户ID查询
                CurrentPage: salecurrentPage.value
            }
        }).then(res => {
            salerows.value = res.data.rows || 0;
            const listData = res.data.list || [];
            // 数据转换
            const Data = listData.map(item => ({
                ...item,
                sale_date: formatDateTimeForSale(new Date(item.sale_date)),
                create_time: formatDateTimeForSale(new Date(item.create_time)),
                approver_time: item.approver_time ? formatDateTimeForSale(new Date(item.approver_time)) : "",
                sale_total: item.sale_total ? parseFloat(item.sale_total).toFixed(2) : "0.00",
                proc_list_full: item.proc_list,
                proc_list: formatProductList(item.proc_list) // 使用上面定义的函数
            }));
            // 按创建时间降序排序 (可选)
            Data.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));
            saledatadata.value = Data;
        }).catch(error => {
            console.error("加载销售记录失败:", error);
            ElMessage.error("加载销售记录失败");
            saledatadata.value = [];
            salerows.value = 0;
        });
      }

      // 销售记录分页处理
      function salehandlePageChange(page) {
          salecurrentPage.value = page;
          SaleLoadData(); // 重新加载数据
      }

      // 销售记录多选数据收集
      function saleSelectChange(val) {
          saleselectdata.value = val;
      }

      // 销售记录导出功能
      function saleExport() {
          if (saleselectdata.value.length == 0) {
              ElMessage({ message: '请选择要导出的数据.', type: 'warning' });
              return;
          }
          const wb = XLSX.utils.book_new();
          const excelData = saleselectdata.value.map((row) => ({
              "销售单号": row.sale_code,
              "单据状态": row.sale_status,
              "销售日期": row.sale_date,
              "客户名称": row.cust_name,
              "联系人": row.cust_linkman,
              "联系方式": row.cust_linkphone,
              "销售部门": row.sale_depName,
              "销售负责人": row.sale_userName,
              "销售数量": row.sale_num,
              "销售金额": row.sale_total,
              "销售货品": row.proc_list,
              "制单人": row.create_name,
              "制单时间": row.create_time,
              "审核人": row.approver_name,
              "审核时间": row.approver_time
          }));
          const ws = XLSX.utils.json_to_sheet(excelData);
          XLSX.utils.book_append_sheet(wb, ws, "销售单");
          // 使用客户名称命名文件 (如果 customerForm.cust_name 可用)
          const filename = `${customerForm.cust_name || '客户'}_销售记录_${new Date().toISOString().slice(0, 10)}.xlsx`;
          XLSX.writeFile(wb, filename);
      }

      // 销售记录跳转详情
      function ShowSaleInfo(row) {
          router.push({
              name: "saleinfo", // 确保你的路由配置中有这个 name
              params: {
                  saleid: row.sale_id,
                  salecode: row.sale_code
              }
          });
      }
      //#endregion
  
      //挂载
      onMounted(() => {
        InLoadData();
        OutLoadData();
        GetIdcustomer();
        GetPublicFile();
        SaleLoadData();
      });
  
      //关闭
      function Close(){
        router.push('customer');
      }
  
      return{
      //#region 销售记录
      saledatadata,
      salecurrentPage,
      salerows,
      saleselectdata,
      salehandlePageChange,
      saleSelectChange,
      saleExport,
      ShowSaleInfo,
      //#endregion
      //#region 出库记录
      ShowOutstockInfo,
      outstockdata,
      outhandlePageChange,
      outSelectChange,
      outExport,
      //#endregion
      //#region 入库记录
      ShowInstockInfo,
      incurrentPage,
      instockdata,
      inhandlePageChange,
      inselectdata,
      inSelectChange,
      inExport,
      //#endregion
        UpdateStatus,
        Close,
        handleRowClick,
        tabs,
        activeTab,
        filter,
        pageSize,
        totalItems,
        customerForm,
        GetIdcustomer,
        deletecustomer,
        JumptoEdit,
        filelist
      }
    }
  }
  </script>
  
  <style scoped>
  /* 底部操作栏自适应 */
  .action-bar {
    position: fixed;
    bottom: 0;
    right: 0.5%; /* 与表单右侧对齐 */
    left: 210px; /* 与菜单栏宽度一致 */
    background: white;
    border-top: 1px solid #e6e6e6;
    padding: 15px;
    text-align: right;
  }
  
  .customer-detail {
    display: flex;
    flex-direction: column;
    gap: 20px;
    padding: 20px;
    width: 70%;
  }
  
  /* 通用样式 */
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
  }
  
  .divider {
    height: 1px;
    background-color: #ebeef5;
    margin: 5px 0 15px;
  }
  
  /* 基础资料容器 */
  .basic-info-container {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    padding: 20px;
  }
  
  .section-title {
    font-size: 18px;
    font-weight: bold;
    color: #1a1a1a;
  }
  
  .section-actions {
    display: flex;
    gap: 10px;
  }
  
  /* 灵活的基础资料网格布局 */
  .basic-info-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr); /* 固定3列 */
    gap: 24px;
  }
  
  @media (max-width: 1200px) {
    .basic-info-grid {
      grid-template-columns: repeat(2, 1fr);
    }
  }
  
  @media (max-width: 768px) {
    .basic-info-grid {
      grid-template-columns: 1fr;
    }
  }
  
  .info-item {
    display: flex;
    min-height: 36px;
  }
  
  .info-label {
    width: 100px;
    color: #1a1a1a;
    font-size: 14px;
    display: flex;
    align-items: center;
  }
  
  .info-value {
    flex: 1;
    font-size: 14px;
    color: #a0a0a0;
    font-weight: 500;
    display: flex;
    align-items: center;
    padding-left: 10px;
  }
  
  /* 跨行显示的元素 */
  .full-row {
    grid-column: 1 / -1;
    display: flex;
  }
  
  .full-row .info-label {
    width: 100px;
  }
  
  .full-row .info-value {
    flex: 1;
  }
  
  /* 其他信息容器 */
  .other-info-container {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    padding: 20px;
  }
  
  .section-tabs {
    display: flex;
    border-bottom: 1px solid #ebeef5;
    width: 100%;
  }
  
  .tab-item {
    padding: 8px 20px;
    cursor: pointer;
    font-size: 14px;
    position: relative;
    color: #606266;
  }
  
  .tab-item.active {
    color: #45b984;
    font-weight: 500;
  }
  
  .tab-item.active::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 100%;
    height: 2px;
    background: #45b984;
  }
  
  /* 灵活的基础资料网格布局 */
  .Additional-Information {
    display: grid;
    grid-template-columns: repeat(2, 1fr); /* 固定3列 */
    gap: 24px;
  }
  
  @media (max-width: 1200px) {
    .Additional-Information {
      grid-template-columns: repeat(2, 1fr);
    }
  }
  
  @media (max-width: 768px) {
    .Additional-Information {
      grid-template-columns: 1fr;
    }
  }
  
  /* 操作记录部分 */
  .filter-section {
    margin-bottom: 20px;
  }
  
  .filter-row {
    display: flex;
    gap: 15px;
    margin-bottom: 10px;
    align-items: center;
    flex-wrap: wrap;
  }
  
  .filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
  }
  
  .filter-label {
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
  }
  
  /* 分页样式 */
  .pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    margin-top: 20px;
  }
  
  .total-items {
    color: #606266;
    font-size: 14px;
  }
  
  .page-size-select {
    display: flex;
    align-items: center;
    color: #606266;
    font-size: 14px;
    gap: 8px;
  }
  </style>